package com.joey.concurrency.example.commUnsafe;

import java.util.Iterator;
import java.util.Vector;

/**
 * @Author hyy
 **/
public class VectorExample2 {

    //ConcurrentModificationException
    //在遍历的过程中不要做更新，在遍历中做好标记，在迭代结束后操作
    private static void test1(Vector<Integer> vector){
        for(Integer i:vector){
            if(i.equals(3)){
                vector.remove(i);
            }
        }
    }
    //ConcurrentModificationException
    private static void test2(Vector<Integer> vector){
        Iterator<Integer> iterator = vector.iterator();
        while (iterator.hasNext()){
            Integer i = iterator.next();
            if(i.equals(3)){
                vector.remove(i);
            }
        }
    }
    //success
    private static void test3(Vector<Integer> vector){
        for(int i = 0;i<vector.size();i++){
            if(vector.get(i).equals(3)){
                vector.remove(i);
            }
        }
    }
    public static void main(String[] args) {
        Vector<Integer> vector = new Vector();
        vector.add(1);
        vector.add(2);
        vector.add(3);
        test1(vector);
//        test2(vector);
//        test3(vector);
    }
}
